﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using XLETL.Model;
using XLETL.Common;
using System.IO;
using System.Collections;

namespace XLETL.TaskManager.Forms
{
  public partial class ViewETLLogs : Form
  {
    const string dateTimeFormat = "yyMMddHHmm";

    TaskInfo currentTaskInfo = null;

    public ViewETLLogs(TaskInfo taskInfo)
    {
      InitializeComponent();

      if (taskInfo == null)
      {
        throw new ArgumentNullException("taskInfo");
      }

      currentTaskInfo = taskInfo;

      this.lblTaskName.Text = taskInfo.TaskDetails.Name;
    }

    private void ViewETLLogs_Load(object sender, EventArgs e)
    {
      if (currentTaskInfo != null)
      {
        string logFolderPath = currentTaskInfo.FileUploadPath;
         DirectoryInfo directory = new DirectoryInfo(logFolderPath);
          FileInfo[] files = directory.GetFiles("*.txt");
          
        // Sort the file list by creation time
          Array.Sort(files, new FileComparer());
        
        string strippedDateTime = "";        
        string displayDatetime = "";
        DateTime parsedDatetime;
        bool isParsed = false;
        List<LogItem> logItems = new List<LogItem>();
        logItems.Add(new LogItem("", "-- Select --"));
                
        foreach (FileInfo file in files)
        {
          strippedDateTime = file.Name.Substring(7, 10);

          isParsed = DateTime.TryParseExact(strippedDateTime, dateTimeFormat, System.Globalization.CultureInfo.InvariantCulture, System.Globalization.DateTimeStyles.None, out parsedDatetime);
          if (isParsed)
          {
            displayDatetime = string.Format("{0}/{1}/{2}-{3}:{4}", parsedDatetime.Day, parsedDatetime.Month, parsedDatetime.Year, parsedDatetime.Hour, parsedDatetime.Minute);
            logItems.Add(new LogItem(file.FullName, displayDatetime));
          }          
        }        

        // Bind the list of log items
        cbLogItems.DataSource = logItems;
        
      }
    }

    private void cbLogItems_SelectedIndexChanged(object sender, EventArgs e)
    {
      // Ignore the first item
      if (cbLogItems.SelectedIndex > 0)
      {
        Cursor.Current = Cursors.WaitCursor;

        LogItem item = (LogItem)cbLogItems.SelectedItem;

        if (!string.IsNullOrEmpty(item.LogPath))
        {
          try
          {
            using (FileStream fs = new FileStream(item.LogPath, FileMode.Open))
            {
              using (StreamReader sr = new StreamReader(fs))
              {
                tbETLLog.Text = sr.ReadToEnd();
              }
            }
          }
          catch (Exception ex)
          {
            tbETLLog.Text = ex.Message;
          }

        }

        Cursor.Current = Cursors.Default;
      }
    }

    private void btnClose_Click(object sender, EventArgs e)
    {
      this.Close();
    }
  }

  /// <summary>
  /// Structure LogItem which holds the file path string and display name in form of creation datetime for the log file 
  /// </summary>
  public struct LogItem
  {
    public string DisplayItem;
    public string LogPath;

    public LogItem(string logPath, string displayItem)
    {
      DisplayItem = displayItem;
      LogPath = logPath;
    }

    public override string ToString()
    {
      return DisplayItem;
    }
  }

  /// <summary>
  /// Custom Comparer class that implement IComparer interface to compare two files by creation time
  /// </summary>
  public class FileComparer : IComparer
  {    
    #region IComparer Members

    public int Compare(object x, object y)
    {
      FileInfo f1 = (FileInfo)x;
      FileInfo f2 = (FileInfo)y;

      return DateTime.Compare(f1.CreationTime, f2.CreationTime);
    }

    #endregion
  }

}
